﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;

namespace RayD.Core
{
    public static class EndpointHelper
    {
        // This helper method comes in 3.0. For now you'll need a copy in your app
        public static Endpoint GetEndpoint(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return context.Features.Get<IEndpointFeature>()?.Endpoint;
        }

        /// <summary>
        /// access action metadata and custom attributes of an action inside middleware handler
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="context">HttpContext</param>
        /// <returns></returns>
        public static T GetMetadata<T>(HttpContext context) where T : Attribute
        {
            var endpoint = GetEndpoint(context);
            // Endpoint will be null if the URL didn't match an action, e.g. a 404 response
            if (endpoint != null)
            {
                return endpoint.Metadata.GetMetadata<T>();
            }
            else
            {
                return null;
            }
        }
    }

}
